package com.liveinstars.im.handler;

import com.liveinstars.im.api.BadWordTransferService;
import com.liveinstars.im.common.enums.IMExceptionEnum;
import com.liveinstars.im.entity.ChatMessage;
import com.liveinstars.im.entity.Msg;
import com.onepiece.cache.service.CacheService;
import com.liveinstars.im.common.exception.IMRuntimeException;
import com.liveinstars.im.core.service.MessageService;
import com.liveinstars.im.corebean.MsgHelper;
import com.onepiece.shipelves.common.utils.CacheUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.liveinstars.im.constant.ServerConstant.MAX_UUID_LIST_SIZE;

/**
 * 1、保持服务器间的心态 2、转发消息
 * 
 * @author ting
 *
 */
@Sharable
@Service
public class ChatHandler extends SimpleChannelInboundHandler<ChatMessage> {

	@Autowired
	private MessageService messageService;

	@Autowired
	private BadWordTransferService badWordTransferService;
	@Autowired
	CacheService cache;

	private static final Logger logger = LoggerFactory.getLogger(ChatHandler.class);

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, ChatMessage message) throws Exception {
		//判断是否含有敏感词
		message.setContent(badWordTransferService.transferWordsToHealth(message.getContent()));
		message.setType(ChatMessage.TYPE_SEND);
		message.setId(messageService.getMsgId());

		//验证是否重发
		String imUserUUIDListKey = CacheUtil.getIMUserUUIDList(message.getFromId());
		boolean sismember = cache.sismember(imUserUUIDListKey, message.getUuid());
		if (sismember) {
			//为重复发送的消息，直接回执
			// 发送回执消息
			logger.info("ChatHandler sismember" + sismember);
			Msg.Message msg = MsgHelper.newReceiptMessage(message.getUuid(), ChatMessage.STATUS_SEND);
			channelHandlerContext.channel().writeAndFlush(msg);
			return;
		} else {
			if (cache.scard(imUserUUIDListKey) > MAX_UUID_LIST_SIZE) {
				logger.info("ChatHandler cache.scard(imUserUUIDListKey) > MAX_UUID_LIST_SIZE");
				cache.spop(imUserUUIDListKey, 50);
			}
			cache.sadd(imUserUUIDListKey, message.getUuid());
		}
		try {
			messageService.sendMessage(message);
			// 发送回执消息
			logger.info("ChatHandler send ReceiptMessage");
			Msg.Message msg = MsgHelper.newReceiptMessage(
					message.getUuid(), ChatMessage.STATUS_SEND);
			channelHandlerContext.channel().writeAndFlush(msg);
		} catch (Exception e) {
			Msg.Message msg;
			if (e instanceof IMRuntimeException) {
				if (((IMRuntimeException) e).getCode().equals(IMExceptionEnum.FAIL_FRIEND_SHIELD.getCode())) {
					msg = MsgHelper.newReceiptMessage(
							message.getUuid(), ChatMessage.STATUS_FAIL_FRIEND_SHIELD);
				} else if (((IMRuntimeException) e).getCode().equals(IMExceptionEnum.FAIL_TEMP_SHIELD.getCode())) {
					msg =  MsgHelper.newReceiptMessage(
							message.getUuid(), ChatMessage.STATUS_FAIL_TEMP_SHIELD);
				} else if (((IMRuntimeException) e).getCode().equals(IMExceptionEnum.FAIL_NOT_MEMBER.getCode())) {
					msg =  MsgHelper.newReceiptMessage(
							message.getUuid(), ChatMessage.STATUS_FAIL_NOT_MEMBER);
				} else if (((IMRuntimeException) e).getCode().equals(IMExceptionEnum.FAIL_BESHIELD.getCode())) {
					msg =  MsgHelper.newReceiptMessage(
							message.getUuid(), ChatMessage.STATUS_FAIL_BESHIELD);
				} else if (((IMRuntimeException) e).getCode().equals(IMExceptionEnum.FAIL_CHAT_GROUP_DISBAND.getCode())) {
					msg =  MsgHelper.newReceiptMessage(
							message.getUuid(), ChatMessage.STATUS_FAIL_CHAT_GROUP_DISBAND);
				} else if (((IMRuntimeException) e).getCode().equals(IMExceptionEnum.FAIL_CHAT_MESSAGE.getCode())) {
					msg =  MsgHelper.newReceiptMessage(
							message.getUuid(), ChatMessage.STATUS_FAIL_MESSAGE);
				} else {
					msg =  MsgHelper.newReceiptMessage(
							message.getUuid(), ChatMessage.STATUS_UNKNOWN);
					logger.error("消息发送未知异常：{}", e.getMessage(), e);
				}
			} else {
				msg = MsgHelper.newReceiptMessage(
						message.getUuid(), ChatMessage.STATUS_UNKNOWN);
				logger.error("消息发送未知异常：{}", e.getMessage(), e);
			}
			channelHandlerContext.channel().writeAndFlush(msg);
		}
		ReferenceCountUtil.release(message);
	}
}